<template>
  <div class="repair-center">
    <div class="personal-info">
      <ul v-infinite-scroll="load" class="infinite-list" style="overflow: auto">
        <!-- 新增报修按钮 -->
        <h2 class="title-style">维修中心</h2>
        <el-button type="primary" @click="showAddRepairDialog = true" style="text-align: right;">新增报修</el-button>

        <!-- 新增报修对话框 -->
        <el-dialog v-model="showAddRepairDialog" title="新增报修">
          <template #default>
            <el-form :model="newRepair" ref="addRepairFormRef" label-width="120px">
              <el-form-item label="房屋名称">
                <el-select v-model="newRepair.houseId" placeholder="请选择房屋名称" :disabled="isSelectingHouse" @change="validateHouseId">
                  <el-option v-for="house in houseList" :key="house.houseId" :label="house.houseName" :value="house.houseId"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="报修问题描述">
                <el-input v-model="newRepair.repairContent" type="textarea" placeholder="请输入报修问题描述" :rules="{ required: true, message: '请输入报修问题描述', trigger: 'blur' }"></el-input>
              </el-form-item>
              <el-form-item label="期望报修时间">
                <el-date-picker
                    v-model="newRepair.repairDate"
                    type="date"
                    placeholder="请选择期望报修时间"
                    :picker-options="{
                    shortcuts: false,
                    format: 'yyyy-MM-dd',
                    valueFormat: 'yyyy-MM-dd'
                  }"
                    :rules="{ required: true, message: '请选择期望报修时间', trigger: 'change' }"
                ></el-date-picker>
              </el-form-item>
            </el-form>
          </template>
          <template #footer>
            <el-button @click="showAddRepairDialog = false">取消</el-button>
            <el-button type="primary" @click="submitAddRepair">提交</el-button>
          </template>
        </el-dialog>

        <!-- 加载中提示 -->
        <div v-if="isLoading" class="loading-container">加载中...</div>

        <!-- 报修列表 -->
        <template v-else-if="repairList && repairList.length > 0">
          <table style="text-align: center; width: 99%; border-collapse: collapse; ">
            <thead>
            <tr>
              <th style="width: 120px; height: 50px; border: 1px solid #eee;">房屋编号</th>
              <th style="width: 180px; height: 50px; border: 1px solid #eee;">报修问题描述</th>
              <th style="width: 120px; height: 50px; border: 1px solid #eee;">创建时间</th>
              <th style="width: 120px; height: 50px; border: 1px solid #eee;">期望报修时间</th>
              <th style="width: 100px; height: 50px; border: 1px solid #eee;">报修状态</th>
              <th style="width: 100px; height: 50px; border: 1px solid #eee;">维修反馈</th>
              <th style="width: 80px; height: 50px; border: 1px solid #eee;">操作</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="(row, index) in repairList" :key="index" style="border: 1px solid #eee;">
              <td style="width: 120px; height: 40px; border: 1px solid #eee;">
                <el-input v-model="row.houseName" disabled class="disabled-style"></el-input>
              </td>
              <td style="width: 180px; height: 40px; border: 1px solid #eee;">
                <el-input v-model="row.content" disabled class="disabled-style"></el-input>
              </td>
              <td style="width: 120px; height: 40px; border: 1px solid #eee;">
                {{ formatDate(row.createTime) }}
              </td>
              <td style="width: 120px; height: 40px; border: 1px solid #eee;">
                {{ formatDate(row.repairDate) }}
              </td>
              <td style="width: 100px; height: 40px; border: 1px solid #eee;">
                <el-input v-model="row.status" disabled class="disabled-style"></el-input>
              </td>
              <td style="width: 100px; height: 40px; border: 1px solid #eee;">
                <el-input v-if="row.feedBack" v-model="row.feedBack" disabled class="disabled-style"></el-input>
                <span v-else>无</span>
              </td>
              <td style="width: 80px; height: 40px; border: 1px solid #eee;">
                <el-button type="danger" @click="confirmCancelRepair(row.id)">取消</el-button>
              </td>
            </tr>
            </tbody>
          </table>
        </template>
        <template v-else>
          <p>暂无维修记录</p>
        </template>
      </ul>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ref } from 'vue'
const count = ref(0)
const load = () => {
  count.value += 2
}
export default {
  name: "RepairCenter",
  data() {
    return {
      showAddRepairDialog: false,
      newRepair: {
        houseId: null, // 修改为 houseId
        repairContent: '',
        repairDate: ''
      },
      addRepairFormRef: null,
      repairList: [],
      isSelectingHouse: false,
      houseList: [],
      formatDate: function (date) {
        if (!date) return '';
        return new Date(date).toLocaleDateString();
      },
      isLoading: false
    };
  },
  mounted() {
    this.fetchRepairList();
    this.fetchHouseList();
  },
  methods: {
    validateHouseId() {
      if (!this.newRepair.houseId) {
        ElMessage.warning('请选择有效的房屋ID');
        this.newRepair.houseId = null;
      }
    },
    async fetchRepairList() {
      this.isLoading = true;
      try {
        const token = localStorage.getItem('token');
        if (!token) {
          ElMessage.error('未获取到token，请重新登录');
          return;
        }
        const response = await axios.get('/api/repair/personal', {
          headers: {
            Authorization: token
          }
        });
        const allRepairs = response.data.data;
        // 排序：未报修的在前，时间近的在前，已报修的在后
        allRepairs.sort((a, b) => {
          if (a.processingStatus === '未处理' && b.processingStatus!== '未处理') {
            return -1;
          }
          if (a.processingStatus!== '未处理' && b.processingStatus === '未处理') {
            return 1;
          }
          return new Date(b.createTime) - new Date(a.createTime);
        });
        this.repairList = allRepairs;
      } catch (error) {
        ElMessage.error('获取报修列表时出错：' + error.message);
      } finally {
        this.isLoading = false;
      }
    },
    async fetchHouseList() {
      this.isLoading = true;
      try {
        const token = localStorage.getItem('token');
        if (!token) {
          ElMessage.error('未获取到token，请重新登录');
          return;
        }
        const response = await axios.get('/api/houses/personal', {
          headers: {
            Authorization: token
          }
        });
        this.houseList = response.data.data;
      } catch (error) {
        ElMessage.error('获取房屋列表时出错：' + error.message);
      } finally {
        this.isLoading = false;
      }
    },
    async submitAddRepair() {
      this.$refs.addRepairFormRef.validate(async (valid) => {
        if (valid) {
          const date = this.newRepair.repairDate;
          if (date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            this.newRepair.repairDate = `${year}-${month}-${day}`;
          }
          try {
            const token = localStorage.getItem('token');
            if (!token) {
              ElMessage.error('未获取到token，请重新登录');
              return;
            }
            const response = await axios.post(`/api/repair/personal/post/${this.newRepair.houseId}`, null, {
              headers: {
                Authorization: token,
                'Content-Type': 'application/json'
              },
              params: {
                content: this.newRepair.repairContent,
                date: this.newRepair.repairDate
              }
            });
            console.log(response)
            if (response.data.code === 200) {
              console.log(this.newRepair.repairContent);
              console.log(this.newRepair.repairDate);
              ElMessage.success('报修提交成功');
              this.showAddRepairDialog = false;
              this.fetchRepairList();
            } else {
              ElMessage.error('报修提交失败,请输入正确信息');
            }
          } catch (error) {
            ElMessage.error('报修提交时出错：' + error.message);
          }
        } else {
          ElMessage.warning('请完善表单信息');
        }
      });
    },
    async confirmCancelRepair(repairId) {
      ElMessageBox.confirm('是否确认取消报修？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const token = localStorage.getItem('token');
          if (!token) {
            ElMessage.error('未获取到token，请重新登录');
            return;
          }
          const response = await axios.put(`/api/repair/cancel/${repairId}`, null, {
            headers: {
              Authorization: token
            }
          });
          console.log('repair',response)
          if (response.data.code === 200) {
            ElMessage.success('取消报修成功');
            this.fetchRepairList();
          } else {
            ElMessage.error('取消报修失败');
          }
        } catch (error) {
          ElMessage.error('取消报修时出错：' + error.message);
        }
      }).catch(() => {
        ElMessage.info('已取消操作');
      });
    }
  }
};
</script>

<style scoped>
.el-button {
  margin-bottom: 20px;
}

.repair-center {
  padding: 15px;
  display: flex;
  width: 100%;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中，可按需选择是否添加 */
}

.personal-info {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 15px;
  width: 80%;
  height: 80%;
  background-color: #ffffff; /* 将背景颜色设置为白色 */
}

.title-style {
  margin-bottom: 20px;
  color: #136bbd;
}

.infinite-list {
  height: 440px;
  padding: 0;
  margin: 0;
  list-style: none;
}
.infinite-list .infinite-list-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  background: var(--el-color-primary-light-9);
  margin: 10px;
  color: var(--el-color-primary);
}
.infinite-list .infinite-list-item + .list-item {
  margin-top: 10px;
}

table {
  width: 80%; /* 调整表格宽度，使其更合适 */
  margin: 0 auto; /* 让表格在父元素中水平居中 */
  border-collapse: collapse;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

table th {
  background-color: #f5f7fa;
  font-weight: bold;
}

table td {
  padding: 12px;
  vertical-align: middle; /* 统一单元格内元素垂直居中 */
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100px;
  font-size: 16px;
  color: #666;
}
</style>